package com.idemon.ds.controller;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.idemon.config.Consts;
import com.idemon.ds.model.Result;
import com.idemon.ds.model.Userinfo;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;

public class LoginController extends Controller {
	private Logger log = Logger.getLogger(getClass());

	public void index() {
		setSessionAttr(Consts.ATTR_KEY_SESSION_BACKUP_URL,getPara("url"));
		render(Consts.DEFAULT_URL_LOGIN);
	}

	public void login() {
		String code = getPara("code");
		Object codeobj = getSessionAttr(Consts.ATTR_KEY_SESSION_VALIDATECODE);
		if (StringUtils.isBlank(code) || codeobj == null || !(code.trim().equalsIgnoreCase(codeobj.toString()))) {
			renderJson(new Result(0, "验证码错误！"));
			return;
		}

		Userinfo user = Userinfo.dao.validate(getPara("name"), getPara("password"));
		if (user == null || user.getName() == null || user.getName().isEmpty()) {
			renderJson(new Result(0, "账号密码错误，请重新输入！"));
			return;
		} else {
			log.info("截止目前登陆过的人数：" + (Consts.LOGIN_USER_COUNT++));
			Userinfo.dao.modifyLastDate(user.getUid());
			setAttr(Consts.ATTR_KEY_SESSION_USER, user);
			setSessionAttr(Consts.ATTR_KEY_SESSION_USER, user);
			Object url = getSessionAttr(Consts.ATTR_KEY_SESSION_BACKUP_URL);
			removeSessionAttr(Consts.ATTR_KEY_SESSION_BACKUP_URL);
			if (url == null) {
				renderJson(new Result(1, PropKit.get(Consts.ATTR_KEY_CONTEXT_PATH, "/")+"index"));
				return;
			} else {
				renderJson(new Result(1, url.toString()));
				return;
			}
		}
	}

	public void logout() {
		removeSessionAttr(Consts.ATTR_KEY_SESSION_USER);
		getSession().invalidate();
		redirect("/index");
	}

	public void islogin() {
		setSessionAttr(Consts.ATTR_KEY_SESSION_BACKUP_URL, getPara("url", Consts.DEFAULT_URL_INDEX));
		Object obj = getSessionAttr(Consts.ATTR_KEY_SESSION_USER);
		if (obj == null) {
			renderJson(0);
		} else {
			renderJson(1);
		}
	}

	public void generatcode() {
		String v_code = getPara("v_code");
		if (StringUtils.isNotBlank(v_code)) {
			setSessionAttr(Consts.ATTR_KEY_SESSION_VALIDATECODE, v_code.trim());
			renderJson(1);
		} else {
			renderJson(0);
		}
	}

	public void validatecode() {
		String code = getPara("code");
		if (StringUtils.isNotBlank(code)) {
			Object obj = getSessionAttr(Consts.ATTR_KEY_SESSION_VALIDATECODE);
			if (obj != null) {
				if (code.trim().equalsIgnoreCase(obj.toString())) {
					renderJson(1);
					return;
				}
			}
		}
		renderJson(0);
	}
}
